package com.bw.module_mine


import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.alibaba.android.arouter.facade.annotation.Route
import com.bw.lib_common.base.BaseMVIActivity
import com.bw.lib_common.livedata_eventbus.Events
import com.bw.lib_common.livedata_eventbuss.LiveEventBus
import com.bw.lib_common.utils.ToastUtils
import com.bw.lib_common.utils.ValidUtils
import com.bw.lib_storage.UserMMKV
import com.bw.module_mine.databinding.ActivityLoginBinding
import com.bw.module_mine.intent.MineIntent
import com.bw.module_mine.state.LoginState
import com.bw.module_mine.viewmodel.MineViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = "/model_mine/LoginActivity")
@AndroidEntryPoint
class LoginActivity : BaseMVIActivity() {
    private var mLoginAgree : Boolean = false
    private val binding : ActivityLoginBinding by lazy {
        ActivityLoginBinding.inflate(layoutInflater)
    }
    private lateinit var mViewModel: MineViewModel
    override fun generateViewModel() {
        mViewModel = ViewModelProvider(this)[MineViewModel::class.java]
    }
    override fun getLayoutRootView(): View {
        return binding.root
    }



    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED) {
                mViewModel.loginState_.collect(){
                    when(it) {
                        is LoginState.Success -> {
                            showMsg("登录成功")
                           // ToastUtils.showLong(this@LoginActivity,"登录成功")
                            UserMMKV.token = it.date.token
                            UserMMKV.userId = it.date.id
                            UserMMKV.userName = it.date.username
                            UserMMKV.accountId = it.date.accountid.toString()
                            // 保存登录返回的头像信息
                            UserMMKV.image = "https://ts1.tc.mm.bing.net/th/id/OIP-C.VnqbqHI999-VVVkUOWBcMwAAAA?rs=1&pid=ImgDetMain&o=7&rm=3"

                            
                            // 发送登录成功广播，通知MineFragment刷新数据
//                            val intent = Intent("com.bw.ivideo.ACTION_LOGIN_SUCCESS")
//                            sendBroadcast(intent)
                            LiveEventBus.with<Boolean>(Events.EVENT_LOGIN_SUCCESS).post(true)
                            finish()

                        }
                        is LoginState.Init -> {

                        }
                        is LoginState.Empty -> {

                        }
                        is LoginState.Error -> {
                            showMsg("登录失败,请检查手机号和密码是否正确")
                        }
                        is LoginState.Loading -> {

                        }
                    }
                }
            }
        }
    }

    override fun initData() {
        super.initData()

    }

    override fun initView() {
        super.initView()
        initAgreementCheckBox(mLoginAgree)
    }

    override fun initEvent() {
        super.initEvent()
        binding.apply {
            cb.setOnClickListener {
                mLoginAgree = !mLoginAgree
                initAgreementCheckBox(mLoginAgree)
            }

            btLogin.setOnClickListener {
                checkPhone()
            }

            tvGoRegister.setOnClickListener {
                routeActivity(RegisterActivity::class.java)
            }
        }
    }

    private fun checkPhone() {
        val phone = binding.etUser1.text.toString()
        val pass = binding.etPass1.text.toString()

        if (!mLoginAgree) {
            ToastUtils.showLong(this,"请先勾选同意《用户协议》和《隐私政策》")
            return
        }

        if (!ValidUtils.phoneNumberValid(phone)) {
            ToastUtils.showLong(this,"请输入正确的手机号码")
            return
        }

        if (pass.isEmpty()) {
            ToastUtils.showLong(this,"密码不能为空")
            return
        }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED) {
                mViewModel.intents.send(MineIntent.Login(phone,pass))
            }
        }
    }

    private fun initAgreementCheckBox(check:Boolean) {
        if (check) {
            binding.cb.background = getDrawable(R.drawable.icon_checked)
        }else{
            binding.cb.background = getDrawable(R.mipmap.icon_uncheck)
        }
    }
}